var customers = null;
var customersObj;
var recordNumber = 0;

chrome.browserAction.setBadgeBackgroundColor({
    color: [255, 0, 0, 255]
});

// 桌面通知：可用于默认加载文件时通知结果
function loadExcelSucess() { //加载文件成功
    chrome.notifications.create("loadExcelSucess", {
        type: 'basic',
        iconUrl: '../images/icon128.png',
        title: '',
        message: '文件加载成功',
    });
}

function loadExcelFail() { //加载文件失败
    chrome.notifications.create("loadExcelFail", {
        type: 'basic',
        iconUrl: '../images/fail72.png',
        title: '',
        message: '文件加载失败',
    });
}

function showCurrentCus(recordNumber) { //显示当前客户名称
    chrome.notifications.create("showCurrentCus", {
        type: 'basic',
        iconUrl: '../images/icon48.png',
        title: '当前客户：',
        message: customersObj[recordNumber].name,
    });
}

// 监听的消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    chrome.notifications.clear("loadExcelSucess");
    chrome.notifications.clear("loadExcelFail");
    chrome.notifications.clear("showCurrentCus");
    //来自popup的消息
    if (request.key == 'load') { //加载popup发送来的客户信息
        customers = request.value;
        if (customers != null && customers != undefined) {
            recordNumber = 0;
            customersObj = JSON.parse(customers);
            loadExcelSucess();
        } else {
            loadExcelFail();
        }
    } else if (request.key == 'loadError') { //前台加载错误
        loadExcelFail();
    } else if (request.key == 'this') { //当前
        getCurrentRecord(recordNumber);
    } else if (request.key == 'next') { //下一条
        ++recordNumber;;
        getCurrentRecord(recordNumber);
    } else if (request.key == 'prev') { //上一条
        if (recordNumber > 0) {
            --recordNumber;
            getCurrentRecord(recordNumber);
        }
    } else if (request.key == 'lookup') { //跳转到
        var numb = request.value;
        recordNumber = numb - 2;
        getCurrentRecord(recordNumber);
        sendMessageToContentScript({
            key: 'record',
            value: customersObj[recordNumber]
        });
    }
});

//显示当前记录内容--推送前台
function getCurrentRecord(number) {
    showCurrentCus(number);
    sendMessageToContentScript({
        key: 'record',
        value: customersObj[number]
    });
}

//向前台发消息
function sendMessageToContentScript(message, callback) {
    chrome.tabs.query({
        active: true
    }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
            if (callback) callback(response);
        });
    });
}